<template>
  <div>
    <!--面包屑 !-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="AddRolesDialog=true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        :data="roles"
        border
        style="width: 100%"
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> 对空格和换行控制  更好看一点 -->
            <el-row :class="['TagBotton',i1==0 ? 'TagTop':'',vcenter]" v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <!-- 渲染一级权限 -->
            <el-col  :span="5">
           <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
           <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级和三级 -->
            <el-col :span="19">
            <el-row :class="[i2==0?'':'TagTop',vcenter]" v-for="(item2,i2) in item1.children" :key="item2.id">
            <el-col  :span="6">
            <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
           <i class="el-icon-caret-right"></i>

            </el-col>
            <el-col  :span="18">
            <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" closable 
            @close="removeRightById(scope.row,item3.id)">
           {{item3.authName}}
            </el-tag>
            </el-col>
            </el-row>
            <el-col></el-col>
            </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          type=index
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        >
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          width="300"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="EditRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="DeleRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="mini"
              @click="ShowSetRightDialog(scope.row)">分配权限</el-button>
          </template>

        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹窗 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddRolesDialog"
      @close="addRolesClosed"
    >
      <el-form
        :model="RolesForm"
        :rules="RolesRules"
        ref="AddRolesFormRef"
      >
        <el-form-item
          label="角色名称"
          prop="Add_EditRolesRule"
        >
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="Add_EditRolesRule"
        >
          <el-input v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确认和取消 -->
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="AddRolesDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="AddRoles()"
        >确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改角色弹窗 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="EditRolesDialog"
    >
      <el-form :model="EditForm">
        <el-form-item label="角色名称">
          <el-input v-model="EditForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="EditForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确认和取消 -->
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="EditRolesDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="PutEditRoles()"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限"  :visible.sync="SetRightDialogVisible" @close="CloseSetRightDialogVisible" >
  <el-tree :data="SetRightList" :props="TressProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="DefKey" ref="TreeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="SetRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="PostRightDialogVisible">确 定</el-button>
  </span>
</el-dialog>
  </div>

</template>

<script>
export default {
  data() {
    return {
      roles: [], //角色信息存储
      RolesForm: {
        //添加角色的存储
        roleName: '',
        roleDesc: '',
      },
      AddRolesDialog: false, //添加弹窗显示
      RolesRules: {
        Add_EditRolesRule: [
          {
            //添加角色规则                    这个规则有问题   true必填 填了也没用   解决不了！！！
            // required: true,
            // message: '角色名称不能为空',
            // trigger: 'blur',
          },
        ],
      },

      EditRolesDialog: false, //修改
      EditForm: {
        //该id 的信息存储
        roleId: 0, //用于提交修改
        roleName: '',
        roleDesc: '',
      },
      // 分配权限
      SetRightDialogVisible:false,
      // 存所有权限值
      SetRightList:[],
      // 树型属性绑定对象
TressProps:{
  label:'authName',
  children:'children'
},
// 默认值
DefKey:[],
// 点击分配权限获取Id值
RolesId:''
    }
  },
  created() {
    this.GetRoles()
  },
  methods: {
    // 获取角色列表数据
    async GetRoles() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roles = res.data
    },
    addRolesClosed() {
      // 关闭弹窗后
      console.log()
      this.$refs.AddRolesFormRef.resetFields()
      this.RolesForm.roleName = '' //重置不了只能这样代替
    },
    //添加用户
    AddRoles() {
      this.$refs.AddRolesFormRef.validate(async (valid) => {
        console.log(valid)
        console.log(this.RolesForm.roleName)

        if (!valid) return this.$message.error('添加失败')
        await this.$http.post('roles', this.RolesForm)
        this.AddRolesDialog = false
        this.GetRoles()
        return this.$message.success('添加角色成功')
      })

      // if (res.meta.status != 201) return this.$message.error('添加角色失败')
      // console.log(res)
      // return this.$message.success('添加角色成功')
    },

    // 修改角色 -----根据ID查询角色
    async EditRoles(scope) {
      this.EditRolesDialog = true
      console.log(scope)
      const { data: res } = await this.$http.get('roles/' + scope)
      console.log(res)
      this.EditForm = res.data //双向绑定    根据id获取到值然后放到data   然后绑定该form
    },
    async PutEditRoles() {
      // 提交到数据库
      console.log(this.EditForm.roleName)
      const { data: res } = await this.$http.put(
        'roles/' + this.EditForm.roleId,
        { roleName: this.EditForm.roleName, roleDesc: this.EditForm.roleDesc }
      )
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.GetRoles()
      this.EditRolesDialog = false
    },
    // 删除
    async DeleRoles(id) {
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status != 200) return this.$message.error('删除失败')
      this.GetRoles()
      return this.$message.success('删除成功')
    },
      // 弹框提示用户是否要删除   
      // 根据id删除权限
    async removeRightById(roleId,RightId){
 const confirmResult=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
console.log(confirmResult)
 if(confirmResult !='confirm') return this.$message.info('取消了删除')
// 如果确认取消
 const {data:res}=await this.$http.delete('roles/'+roleId.id+'/rights/'+RightId)
 if(res.meta.status != 200){
  return this.$message.error('删除失败')
 }
 roleId.children=res.data     //把roleid，children=>整个列重赋值
 console.log(roleId.children)
//  this.GetRoles()   这个是整体的刷新了  
return this.$message.success('已了删除')
      },

// 分配权限
async ShowSetRightDialog(scope){
  this.RolesId=scope.id
  // 获取所有权限的数据
const {data:res}=await this.$http.get('rights/tree')
if(res.meta.status !=200) return this.$message.error('获取所有权限的数据失败')
this.SetRightList=res.data
this.GetLeafKeys(scope,this.DefKey)
this.SetRightDialogVisible=true
},
// 获取子节点的id
GetLeafKeys(node,arr){
  if(!node.children) return arr.push(node.id)//push 在此数组末尾添加
   node.children.forEach(item => {
    this.GetLeafKeys(item,arr)
    console.log(item)
   }
   )
},
// 关闭后清空默认值  不然会保存下来  越来越多
CloseSetRightDialogVisible(){
  console.log('jgyft')
  this.DefKey=[]
},
  // 提交分配权限
async PostRightDialogVisible(){ 
const TreeKeys=[
  this.$refs.TreeRef.getCheckedKeys(),//完全选择
  this.$refs.TreeRef.getHalfCheckedKeys()//半选择
]
const idStr = TreeKeys.join(',')//应用文档拼接
const {data:res}= await this.$http.post(`roles/`+this.RolesId+`/rights`,{rids:idStr})
 console.log(this.RolesId)
if(res.meta.status!=200) return this.$message.error('添加权限失败')
this.$message.success('添加权限成功')
this.GetRoles()//刷新
this.SetRightDialogVisible=false
},
}
}
</script>

<style scoped lang="less">
.el-tag{
  margin:7px;
}
.TagTop{
  border-top:1px solid #eee;
}
.TagBotton{
  border-bottom:1px solid #eee;

}
.vcenter{
  display: flex;
align-items:center;
}

</style>
 